package ru.yelbota.flex.as3jobs.libs {
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;

import ru.yelbota.flex.as3jobs.Job;
import ru.yelbota.flex.as3jobs.as3_jobs;
import ru.yelbota.flex.as3jobs.exceptions.JobWaitEventException;

use namespace as3_jobs;

[Event(type="flash.events.Event", name="complete")]

public class EventWaiter extends EventDispatcher {

    private var event:Event;

    public function EventWaiter(dispatcher:IEventDispatcher, event:String):void {
        dispatcher.addEventListener(event, handler);
    }

    private function handler(event:Event):void {
        this.event = event;
        dispatchEvent(new Event(Event.COMPLETE));
    }

    public static function waitForEvent(dispatcher:IEventDispatcher, event:String):Event {

        Job.incrementCallIndex();

        const rname:String = "EventWaiter$" + Job.getCurrentCallIndex();
        const resource:EventWaiter = EventWaiter(Job.getResource(Job.getCurrentJob(), rname));

        if (resource == null) {
            const waiter:EventWaiter = new EventWaiter(dispatcher, event);
            throw new JobWaitEventException(Event.COMPLETE, waiter, rname);
        }
        else return resource.event;
    }

    public static function waitForComplete(dispatcher:IEventDispatcher):Event {
        return waitForEvent(dispatcher, Event.COMPLETE);
    }
}

}
